const get = createGetter();
const set = createSetter();

function createGetter(shallow = false) {
  return function (target, key, receiver) {
    console.log("target-get=", target);
    const res = Reflect.get(target, key, receiver);
    console.log("res-get==", res);
    track(target, "get", key);
    if (typeof res === "object") {
      return shallow ? res : reactive(res);
    }
    return res;
  };
}
function createSetter() {
  return function (target, key, value, receiver) {
    const res = Reflect.set(target, key, value, receiver);
    console.log("setsetset", res);
    trigger(target, "set", key);
    return res;
  };
}
const tragetMap = new Map();
// const tragetMap = {
//   target1: {
//     key1: [回调函数1, 回调函数2],
//     key2: [回调函数3],
//   },
//   target2: {
//     key1: [回调函数4],
//     key2: [回调函数5],
//   },
// };
const track = (target, type, key) => {
  let depsMap = tragetMap.get(target);
  if (!depsMap) {
    tragetMap.set(target, (depsMap = new Map()));
  }
  let keyDeps = depsMap.get(key);
  console.log("是否已存在!keyDeps=", !keyDeps);
  if (!keyDeps) {
    keyDeps = new Set();
  }
  if (!keyDeps.has(activiteEffect) && activiteEffect) {
    keyDeps.add(activiteEffect);
  }
  depsMap.set(key, keyDeps);
  console.log("tragetMap==", tragetMap);
};
const trigger = (target, type, key) => {
  let depsMap = tragetMap.get(target);
  if (!depsMap) {
    return;
  }
  const keyDeps = depsMap.get(key);
  if (!keyDeps) {
    return;
  }
  keyDeps.forEach((effect) => {
    if (effect.scheduler) {
      effect.scheduler();
    } else {
      effect();
    }
  });
};

let activiteEffect = null;
export const effect = (fn, options = {}) => {
  const effectFn = () => {
    try {
      activiteEffect = effectFn;
      return fn();
    } finally {
      activiteEffect = null;
    }
  };
  if (!options.lazy) {
    effectFn();
  }

  effectFn.scheduler = options.scheduler;
  console.log("effectFn==", effectFn);
  return effectFn;
};
export const mutableHandles = {
  get,
  set,
};
